package org.joe.chinachess.resources;

import org.joe.chinachess.utils.Constants;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 读入图片信息到内存中
 *
 * @author Joe
 */
public final class ResourceLoader {

    // 一维key存放颜色，二维key存棋子，数组下标为状态
    private static Map<Integer, Map<Integer, Image[]>> pictures;

    static {
        pictures = new HashMap<>();
        String picRoot = ResourceLoader.class.getClassLoader().getResource(".").getFile() + File.separator + "pic";
        System.out.println();
        File unKnowFile = new File(picRoot + File.separator + "U0.png");
        Image unKnowImage = null;
        try {
            unKnowImage = ImageIO.read(unKnowFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        File file = new File(picRoot);
        File[] files = file.listFiles();
        for (File f : files) {
            Image image = null;
            try {
                image = ImageIO.read(f);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String name = f.getName();
            if ("U0.png".equals(name)) {
                continue;
            }
            char color = name.charAt(0);
            int chess = Integer.valueOf(name.charAt(1)+"");
            char state = name.charAt(2);
            Map<Integer, Image[]> map = null;
            if (color == 'R') {
                map = pictures.get(Constants.Color.RED);
                if (map == null) {
                    map = new HashMap();
                    pictures.put(Constants.Color.RED, map);
                }
            } else if (color == 'B') {
                map = pictures.get(Constants.Color.BLACK);
                if (map == null) {
                    map = new HashMap();
                    pictures.put(Constants.Color.BLACK, map);
                }
            } else {
                map = pictures.get(Constants.Color.STUB);
                if (map == null) {
                    map = new HashMap();
                    pictures.put(Constants.Color.STUB, map);
                }
            }

            Image[] images = map.get(chess);
            if (images == null) {
                images = new Image[3];
                images[0] = unKnowImage;
                map.put(chess, images);
            }

            images[state == 'S' ? Constants.Status.SELECT : Constants.Status.UNSELECT] = image;
            map.put(chess, images);
        }
    }

    public final static Map<Integer, Map<Integer, Image[]>> getPictures() {
        return pictures;
    }

}
